using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.DTOS;
using SmartLink.DTOS.Permission;
using SmartLink.Application.IServices;
using SmartLink.Domain;
using SmartLink.Domain.Entity;
using SmartLink.Domain.Services;
using SmartLink.EnumLibrary;
using SmartLink.Infrastructure;
using SmartLink.Infrastructure.Cache;
using SmartLink.IRepository;
using SmartLink.Repository;
using SmartLink.Domain.IServices;
using SmartLink.DTOS.SysBasic;
using SmartLink.Code;

namespace SmartLink.Application.Services
{
    public class PermissionAppServices : IPermissionAppServices
    {
        private ISYS_MenuServices _sysMenuServices;
        private IPermissionServices _permissionServices;
        private ISysModuleServices _sysModuleServices;

        public PermissionAppServices(ISYS_MenuServices iSYS_MenuServices,
                                     IPermissionServices permissionServices,
                                     ISysModuleServices sysModuleServices)
        {
            _sysMenuServices = iSYS_MenuServices;
            _permissionServices = permissionServices;
            _sysModuleServices = sysModuleServices;
        }

        public IList<PermissionListItemDTO> GetRolePermissions(int roleId)
        {
            IList<PermissionListItemDTO> rolePermissions = Mapper.Map<List<PermissionListItemDTO>>(_permissionServices.GetAuthorizedModules(AuthorizationOwnerTypeEnum.Role, roleId));
            var ownFunctions = _permissionServices.GetAuthorizedFunctions(AuthorizationOwnerTypeEnum.Role, roleId);
            var dataAuthrizations = _permissionServices.GetDataAuthorization(AuthorizationOwnerTypeEnum.Role, roleId);
            foreach (var modulePermission in rolePermissions)
            {
                //modulePermission.Functions = Mapper.Map<IList<SysModuleFunctionNodeDTO>>(ownFunctions.Where(a => a.ModuleCode.Equals(modulePermission.Code)));

                //为将来可能配置多项的情况做处理
                var moduleDataAuthrizationGrps = dataAuthrizations.Where(a => a.ModuleCode.Equals(modulePermission.Code))
                                                    .GroupBy(a => a.AuthorizationScope).OrderBy(a => a.Key).ToList();
                if (moduleDataAuthrizationGrps.Count > 0)
                {
                    modulePermission.DataAuthorization = new List<DataAuthorizationItemDTO>();
                    foreach (var group in moduleDataAuthrizationGrps)
                    {
                        modulePermission.DataAuthorization.Add(new DataAuthorizationItemDTO
                        {
                            AuthorizationScope = group.Key,
                            AuthorizationScopeText = EnumHelper.GetDesription(group.First().AuthorizationScope),
                            BeApplied = true,
                            CustomResourseIds = group.Where(a => a.CustomResourceID.HasValue).Select(a => a.CustomResourceID.Value).ToList()
                        });
                    }
                }
            }
            return rolePermissions;
        }

        public Results<IList<PermissionListItemViewDTO>> GetRolePermissionsToSetting(int roleId)
        {
            var modules = _sysModuleServices.GetAllWithRelation();
            var functions = _sysModuleServices.GetAllFunction();
            var ownModuleIds = _permissionServices.GetAuthorizedModules(AuthorizationOwnerTypeEnum.Role, roleId).Select(a => a.ID);
            var ownFunctionIds = _permissionServices.GetAuthorizedFunctions(AuthorizationOwnerTypeEnum.Role, roleId).Select(a => a.ID);
            var fakeTreeList = SysModuleAppServices.ConvertToModuleAndFunctionsList(modules, functions);
            foreach (var moduleItem in fakeTreeList)
            {
                if (ownModuleIds.Contains(moduleItem.ModuleID))
                    moduleItem.Flag = true;
                //foreach (var functionItem in moduleItem.Functions)
                //{
                //    if (ownFunctionIds.Contains(functionItem.FunctionID))
                //        functionItem.Flag = true;
                //}
            }
            //数据权限
            IList<PermissionListItemViewDTO> allConfigurablePermissions = Mapper.Map<List<PermissionListItemViewDTO>>(fakeTreeList);
            Dictionary<ModuleCodeEnum, HashSet<AuthorizationScopeEnum>> allModuleDataAuthorizeRules = DataAuthorizeRule.Instance.Rules;

            IList<PermissionListItemDTO> rolePermissions = null;
            if (rolePermissions == null) rolePermissions = GetRolePermissions(roleId);

            var enumDscptsDic = EnumHelper.GetFiledsDescriptions<AuthorizationScopeEnum>();
            foreach (var moduleRule in allModuleDataAuthorizeRules)
            {
                var configurableModulePermission = allConfigurablePermissions.Where(a => a.Code.Equals(moduleRule.Key.ToString())).SingleOrDefault();
                if (configurableModulePermission != null)
                {
                    //configurableModulePermission.DataAuthorization = moduleRule.Value.Select(scopeEnum => new DataAuthorizationItemDTO
                    //{
                    //    AuthorizationScope = scopeEnum,
                    //    AuthorizationScopeText = enumDscptsDic[scopeEnum].ToString(),
                    //    BeApplied = false
                    //}).OrderBy(a => a.AuthorizationScope).ToList();
                    //var ownModulePermission = rolePermissions.Where(item => item.Code.Equals(configurableModulePermission.Code)).SingleOrDefault();
                    //if (ownModulePermission != null &&
                    //    ownModulePermission.DataAuthorization != null && ownModulePermission.DataAuthorization.Count > 0)
                    //{
                    //    foreach (var dataAuthed in ownModulePermission.DataAuthorization)
                    //    {
                    //        var configurableItem = configurableModulePermission.DataAuthorization.Where(item => item.AuthorizationScope == dataAuthed.AuthorizationScope).SingleOrDefault();
                    //        if (configurableItem != null)
                    //        {
                    //            configurableItem.BeApplied = true;
                    //            configurableItem.CustomResourseIds = dataAuthed.CustomResourseIds;
                    //            //当前业务约束仅有一项选中
                    //            //configurableModulePermission.AppliedDataAuthorization = configurableItem;
                    //        }
                    //    }
                    //}
                }
            }

            return InfrastructureAppService.Response(allConfigurablePermissions);
        }

        public Results<IList<int>> GetRoleDataPermissions(int roleId)
        {
            IList<int> reDataPermissions = new List<int>();
            try
            {
                //缓存
                reDataPermissions = UserInfoCaches.GetDataRights(roleId);
                if (reDataPermissions == null)
                {
                    IList<PER_DataPermissions> dataPermissions = _permissionServices.GetDataPermissionsByUserId(roleId);
                    reDataPermissions = dataPermissions.Select(one => one.ODID).ToList();
                    if (reDataPermissions.Count != 0)
                        UserInfoCaches.SetDataRights(roleId, reDataPermissions);
                }
                return InfrastructureAppService.Response<IList<int>>(reDataPermissions);
            }
            catch (Exception ex)
            {
                return InfrastructureAppService.Response<IList<int>>(new List<int>(), "获取数据权限失败", StateCodeEnum.失败.GetHashCode());
            }
        }

        public Results AllotToRole(int roleId, IEnumerable<PermissionListItemViewDTO> model)
        {
            var moduleIds = model.Where(m => m.Flag == true).Select(a => a.ModuleID);
            moduleIds = CompleteAncestorIds(moduleIds);
            var functionIds = new List<int>(); // model.Where(m => m.Flag == true).SelectMany(m => m.Functions.Where(f => f.Flag == true).Select(f => f.FunctionID));
            //var moduleDataAuthorizations = model.Where(m => m.Flag == true).Where(a => a.AppliedDataAuthorization != null).ToDictionary(m => m.Code,
            //    m => new DataAuthorizationItemDTO[] { m.AppliedDataAuthorization }.AsEnumerable());
            _permissionServices.Allot(AuthorizationOwnerTypeEnum.Role, roleId, moduleIds, functionIds, new Dictionary<string, IEnumerable<DataAuthorizationItemDTO>>());
            //缓存操作
            var rolePermissions = GetRolePermissions(roleId);
            RolePermissionCache.Set(roleId, rolePermissions);
            var roleUserIds = RoleToUsersCache.GetUsers(roleId);
            if (roleUserIds != null && roleUserIds.Count > 0)
            {
                foreach (var userId in roleUserIds)
                {
                    UserInfoCaches.SetExpires(userId);
                }
            }
            return InfrastructureAppService.Response();
        }

        /// <summary>
        /// 用模块的祖辈ID补全模块集合
        /// </summary>
        /// <param name="moduleIds"></param>
        /// <returns></returns>
        private IEnumerable<int> CompleteAncestorIds(IEnumerable<int> moduleIds)
        {
            var all = _sysModuleServices.GetAllWithRelation();
            var completedHs = new HashSet<int>(moduleIds);
            foreach (var item in moduleIds)
            {
                completedHs.Add(item);
                var path = all.Where(a => a.ID == item).Select(a => a.Path).SingleOrDefault();
                if (!string.IsNullOrEmpty(path))
                {
                    var pids = Array.ConvertAll(path.Split(','), a => int.Parse(a));
                    foreach (var pid in pids)
                    {
                        completedHs.Add(pid);
                    }
                }
            }
            return completedHs;
        }

        private IEnumerable<int> GetTreeModuleIds(IEnumerable<SysModuleFunctionTreeNodeDTO> treeModel)
        {
            var moduleIds = new List<int>();
            foreach (var node in treeModel)
            {
                moduleIds.AddRange(GetFieldRecursive(node, a => a.ModuleID));
            }
            return moduleIds;
        }
        private IEnumerable<int> GetTreeFunctionIds(IEnumerable<SysModuleFunctionTreeNodeDTO> treeModel)
        {
            var functions = new List<int>();
            foreach (var node in treeModel)
            {
                functions.AddRange(GetFieldRecursive(node, a => a.Functions.Select(f => f.FunctionID)).SelectMany(a => a));
            }
            return functions;
        }
        private IEnumerable<TResult> GetFieldRecursive<TResult>(SysModuleFunctionTreeNodeDTO nodeModel, Func<SysModuleFunctionTreeNodeDTO, TResult> selector)
        {
            var fieldList = new List<TResult> { selector(nodeModel) };
            if (nodeModel.Children != null && nodeModel.Children.Count > 0)
            {
                foreach (var childNode in nodeModel.Children)
                {
                    fieldList.AddRange(GetFieldRecursive(childNode, selector));
                }
            }
            return fieldList;
        }

        #region old

        #region 菜单基本管理

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="menuDto"></param>
        /// <returns></returns>
        public DTOS.Results Add(InMenuDTO menuDto)
        {
            DTOS.Results results = new DTOS.Results();
            SYS_Menu menuAdd = Mapper.Map<InMenuDTO, SYS_Menu>(menuDto);
            menuAdd.CreateTime = DateTime.Now;
            SYS_Menu maxSortMenu = _sysMenuServices.GetMaxSortMenuByParentId(menuDto.ParentID);
            if (maxSortMenu == null)
                menuAdd.Sort = 1;
            else
                menuAdd.Sort = maxSortMenu.Sort + 1;
            if (menuDto.ParentID == -1)
                menuAdd.ParentIDIndex = "-1";
            else
            {
                SYS_Menu parentMenu = _sysMenuServices.GetSingleMenu(menuDto.ParentID);
                menuAdd.ParentIDIndex = parentMenu.ParentIDIndex + "_" + menuDto.ParentID;
            }
            //menuAdd.Creator = 1;

            bool existMenuUrl = false;
            if (menuDto.Url.Trim().Length > 0)
                existMenuUrl = _sysMenuServices.CheckExistByMenuUrl(menuDto.Url);
            if (existMenuUrl)
            {
                results.State = StateCodeEnum.失败.GetHashCode();
                results.Message = "菜单Url已经存在!";
                return results;
            }

            bool existMenuNamFlag = _sysMenuServices.CheckExistSameLevelMenuByMenuName(menuDto.ParentID, menuDto.MenuName);
            if (existMenuNamFlag)
            {
                results.State = StateCodeEnum.失败.GetHashCode();
                results.Message = "菜单已经存在!";
                return results;
            }

            _sysMenuServices.Add(menuAdd);
            results.State = StateCodeEnum.成功.GetHashCode();
            results.Message = StateCodeEnum.成功.ToString();
            return results;
        }

        /// <summary>
        /// 更新菜单
        /// </summary>
        /// <param name="menuDto"></param>
        /// <returns></returns>
        public Results Update(UpDateMenuDto menuDto)
        {
            Results results = new DTOS.Results();

            bool existMenuUrl = false;
            SYS_Menu curMenu = _sysMenuServices.GetSingleMenu(menuDto.ID);

            if (curMenu.Url != menuDto.Url)
                existMenuUrl = _sysMenuServices.CheckExistByMenuUrl(menuDto.Url);
            if (existMenuUrl)
            {
                results.State = StateCodeEnum.失败.GetHashCode();
                results.Message = "菜单Url已经存在!";
                return results;
            }

            bool existMenuNamFlag = false;
            if (curMenu.MenuName != menuDto.MenuName)
                existMenuNamFlag = _sysMenuServices.CheckExistSameLevelMenuByMenuName(curMenu.ParentID, menuDto.MenuName);
            if (existMenuNamFlag)
            {
                results.State = StateCodeEnum.失败.GetHashCode();
                results.Message = "菜单已经存在!";
                return results;
            }

            SYS_Menu menuUpDate = Mapper.Map<UpDateMenuDto, SYS_Menu>(menuDto);
            SYS_Menu origiMenu = _sysMenuServices.GetSingleMenu(menuDto.ID);
            origiMenu.MenuName = menuUpDate.MenuName;
            origiMenu.Url = menuUpDate.Url;
            origiMenu.IconName = menuUpDate.IconName;
            bool sucFlag = _sysMenuServices.Update(origiMenu);
            if (sucFlag)
                return InfrastructureAppService.Response();
            else
                return InfrastructureAppService.Response(StateCodeEnum.失败.ToString(), StateCodeEnum.失败.GetHashCode());
        }

        public Results Delete(DeleteIDDto deleteDto)
        {
            Results results = new DTOS.Results();
            bool sucFlag = _sysMenuServices.Delete(deleteDto.ID);
            if (sucFlag)
                return InfrastructureAppService.Response();
            else
                return InfrastructureAppService.Response(StateCodeEnum.失败.ToString(), StateCodeEnum.失败.GetHashCode());
        }

        /// <summary>
        ///获取单个menu详细信息
        /// </summary>
        /// <param name="menuId"></param>
        /// <returns></returns>
        public Results<MenuDTO> GetSingleMenu(GetIDDTO getDTO)
        {
            Results<MenuDTO> results = new DTOS.Results<MenuDTO>();
            SYS_Menu menu = _sysMenuServices.GetSingleMenu(getDTO.ID);
            if (menu != null)
                results.State = StateCodeEnum.失败.GetHashCode();

            MenuDTO menuDto = Mapper.Map<SYS_Menu, MenuDTO>(menu);
            results.Data = menuDto;
            return results;
        }

        #endregion

        #region 菜单权限

        public Results<TreeNode> GetAllMenuTreeByUserRight(int userId)
        {
            Results<TreeNode> results = new DTOS.Results<TreeNode>();
            TreeNode treeData;
            IList<int> rightMenuIds = new List<int>();
            IList<SYS_Menu> rightMenus = new List<SYS_Menu>();
            Dictionary<int, bool> dicRightMenus = new Dictionary<int, bool>();
            try
            {
                IList<SYS_Menu> allMenus = _sysMenuServices.GetMenusByIds(new List<int>());
                if (userId != 0)
                {
                    rightMenuIds = _sysMenuServices.GetUserMenuIds(userId);
                    dicRightMenus = rightMenuIds.ToDictionary(one => one, one => true);
                }
                treeData = GetTree(allMenus, dicRightMenus);
            }
            catch (Exception ex)
            {
                return InfrastructureAppService.Response<TreeNode>(null, StateCodeEnum.系统异常.ToString(), StateCodeEnum.失败.GetHashCode());
            }
            return InfrastructureAppService.Response<TreeNode>(treeData);
        }

        /// <summary>
        ///获取角色的权限菜单
        /// </summary>
        /// <param name="roldId"></param>
        /// <returns></returns>
        public Results<TreeNode> GetAllMenuTreeByRole(int roldId, int UserId)
        {
            CurrentUserInfo curUserInfo = UserInfoCaches.GetUserInfoCache(UserId);

            Results<TreeNode> results = new DTOS.Results<TreeNode>();
            TreeNode treeData;
            IList<int> rightMenuIds = new List<int>();
            IList<SYS_Menu> rightMenus = new List<SYS_Menu>();
            Dictionary<int, bool> dicRightMenus = new Dictionary<int, bool>();
            try
            {
                IList<SYS_Menu> allMenus = _sysMenuServices.GetAllMenus();
                if (curUserInfo.RoleName == ConstData.OrgManagerRoleName)
                    allMenus = allMenus.Where(one => one.MenuName != "后台管理").ToList();

                if (roldId != 0)
                {
                    rightMenuIds = _sysMenuServices.GetRoleMenuIds(roldId);
                    dicRightMenus = rightMenuIds.ToDictionary(one => one, one => true);
                }
                treeData = GetTree(allMenus, dicRightMenus);
            }
            catch (Exception ex)
            {
                return InfrastructureAppService.Response<TreeNode>(null, StateCodeEnum.系统异常.ToString(), StateCodeEnum.失败.GetHashCode());
            }
            return InfrastructureAppService.Response<TreeNode>(treeData);
        }

        /// <summary>     
        /// 获取所有菜单，用于编辑
        /// </summary>
        /// <returns></returns>
        public Results<TreeNode> GetAllMenuTree()
        {
            Results<TreeNode> results = new DTOS.Results<TreeNode>();
            TreeNode treeData;
            List<int> menuIds = new List<int>();
            IList<SYS_Menu> allMenus = new List<SYS_Menu>();
            allMenus = _sysMenuServices.GetAllMenus();
            treeData = GetTree(allMenus);
            return InfrastructureAppService.Response(treeData);
        }

        /// <summary>
        /// 获取有权限的菜单
        /// </summary>
        /// <returns></returns>
        public Results<TreeNode> GetRightMenuTree(int curUserId)
        {
            Results<TreeNode> results = new DTOS.Results<TreeNode>();
            TreeNode treeData;
            //获取用户角色下的菜单权限service
            IList<int> menuIds = _sysMenuServices.GetUserMenuIds(curUserId);
            IList<SYS_Menu> menus = new List<SYS_Menu>();

            treeData = UserInfoCaches.GetRightsMenus(curUserId);
            if (treeData == null)
            {
                menus = _sysMenuServices.GetMenusByIds(menuIds);
                treeData = GetTree(menus);
                UserInfoCaches.SetRightsMenus(curUserId, treeData);
            }

            return InfrastructureAppService.Response(treeData);
        }

        #endregion 

        #region  动作权限

        /// <summary>
        /// 用户的动作权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Results<IList<string>> GetActionPermissions(int userId)
        {
            IList<string> actions = new List<string>();
            try
            {
                //缓存
                actions = UserInfoCaches.GetRightsActions(userId);
                if (actions == null)
                {
                    IList<PER_ActionPermissions> actionPermissions = _permissionServices.GetActionPermissionsByUserId(userId);
                    actions = actionPermissions.Select(ap => string.Format("{0}_{1}", ap.Controlname.ToLower(), ap.Actionname.ToLower())).ToList();
                    if (actions.Count != 0)
                        UserInfoCaches.SetRightsActions(userId, actions);
                }
                return InfrastructureAppService.Response<IList<string>>(actions);
            }
            catch (Exception ex)
            {
                return InfrastructureAppService.Response<IList<string>>(new List<string>(), "获取动作权限失败", StateCodeEnum.失败.GetHashCode());
            }
        }

        /// <summary>
        /// 获取行为权限操作界面数据
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Results<IList<ActionPermissionGroupDTO>> GetActionPermissionGroups(int userId)
        {
            IList<ActionPermissionGroupDTO> reDtos = new List<ActionPermissionGroupDTO>();
            try
            {
                IList<PER_ActionPermissions> curUserActionPermissions = _permissionServices.GetActionPermissionsByUserId(userId);
                //用户行为权限数据入缓存


                IList<PER_ActionPermissions> allActionPermissions = _permissionServices.GetAllActionPermissions();
                IList<PER_PermissionsGroup> permissionsGroups = _permissionServices.GetAllPermissionsGroup();
                //用户拥有的行为权限
                Dictionary<int, bool> dicIdHasRights = curUserActionPermissions.ToDictionary(one => one.ID, one => true);
                //所有的行为权限
                Dictionary<int, string> dicIdToPermissionTitle = allActionPermissions.ToDictionary(one => one.ID, one => one.PermissionTitle);
                foreach (PER_PermissionsGroup pg in permissionsGroups)
                {
                    ActionPermissionGroupDTO actionPermissionGroupDTO = new ActionPermissionGroupDTO();
                    actionPermissionGroupDTO.PermissionName = pg.PermissionName;
                    IList<ActionPermissionItemDTO> items = new List<ActionPermissionItemDTO>();
                    string[] ids = pg.PermissionIDs.Split(',');
                    foreach (string id in ids)
                    {
                        ActionPermissionItemDTO itemDto = new ActionPermissionItemDTO();
                        itemDto.ActionId = Convert.ToInt32(id);
                        itemDto.HasRight = dicIdHasRights.ContainsKey(itemDto.ActionId);
                        itemDto.PermissionItemName = dicIdToPermissionTitle.ContainsKey(itemDto.ActionId) == true ? dicIdToPermissionTitle[itemDto.ActionId] : "";
                        items.Add(itemDto);
                    }
                    actionPermissionGroupDTO.Actions = items;
                    reDtos.Add(actionPermissionGroupDTO);
                }
            }
            catch (Exception ex)
            {
                return InfrastructureAppService.Response<IList<ActionPermissionGroupDTO>>("获取行为权限初始数据失败", StateCodeEnum.失败.GetHashCode());
            }

            return InfrastructureAppService.Response<IList<ActionPermissionGroupDTO>>(reDtos, "获取行为权限初始数据成功", StateCodeEnum.成功.GetHashCode());
        }

        #endregion

        #region 数据权限

        public Results<IList<int>> GetDataPermissions(int userId)
        {
            IList<int> reDataPermissions = new List<int>();
            try
            {
                //缓存
                reDataPermissions = UserInfoCaches.GetDataRights(userId);
                if (reDataPermissions == null)
                {
                    IList<PER_DataPermissions> dataPermissions = _permissionServices.GetDataPermissionsByUserId(userId);
                    reDataPermissions = dataPermissions.Select(one => one.ODID).ToList();
                    if (reDataPermissions.Count != 0)
                        UserInfoCaches.SetDataRights(userId, reDataPermissions);
                }
                return InfrastructureAppService.Response<IList<int>>(reDataPermissions);
            }
            catch (Exception ex)
            {
                return InfrastructureAppService.Response<IList<int>>(new List<int>(), "获取数据权限失败", StateCodeEnum.失败.GetHashCode());
            }
        }

        #endregion

        #region private 方法

        private TreeNode GetTree(IList<SYS_Menu> menus, Dictionary<int, bool> dicRightMenu = null)
        {
            var treeRoot = new TreeNode { ID = -1, MenuName = "所有菜单", Url = "" };

            Dictionary<int, List<TreeNode>> dicIdToChilds = new Dictionary<int, List<TreeNode>>();
            foreach (var item in menus)
            {
                bool hasRight = true;
                if (dicRightMenu != null && !dicRightMenu.ContainsKey(item.ID))
                    hasRight = false;

                var node = new TreeNode
                {
                    ID = item.ID,
                    MenuName = item.MenuName,
                    Url = item.Url,
                    IconName = item.IconName,
                    HasRight = hasRight
                };
                if (dicIdToChilds.Keys.Contains(item.ParentID))
                {
                    dicIdToChilds[item.ParentID].Insert(dicIdToChilds[item.ParentID].Count, node);
                }
                else
                {
                    dicIdToChilds.Add(item.ParentID, new List<TreeNode> { node });
                }
            }
            SetChildNodes(treeRoot, dicIdToChilds);

            return treeRoot;
        }

        private void InitData(IList<SYS_Menu> menus, TreeNode rootNode)
        {
            Dictionary<int, List<TreeNode>> dicIdToChilds = new Dictionary<int, List<TreeNode>>();
            foreach (var item in menus)
            {
                var node = new TreeNode
                {
                    ID = item.ID,
                    MenuName = item.MenuName,
                    Url = item.Url,
                    IconName = item.IconName
                };
                if (dicIdToChilds.Keys.Contains(item.ParentID))
                {
                    dicIdToChilds[item.ParentID].Insert(dicIdToChilds[item.ParentID].Count, node);
                }
                else
                {
                    dicIdToChilds.Add(item.ParentID, new List<TreeNode> { node });
                }
            }
            SetChildNodes(rootNode, dicIdToChilds);
        }

        private void SetChildNodes(TreeNode node, Dictionary<int, List<TreeNode>> dic)
        {
            if (!dic.Keys.Contains(node.ID))
            {
                return;
            }
            node.SubLinks = dic[node.ID];
            foreach (var item in node.SubLinks)
            {
                SetChildNodes(item, dic);
            }
        }

        #endregion

        #endregion
    }
}
